<template>
  <div class="user-container">
    <p class="common-list-bread">用户组管理</p>
    <div class="common-query-box">
      <el-form :inline="true" labelWidth="90px">
        <el-form-item label="用户组名称：">
          <el-select
            v-model="name"
            placeholder="请选择"
            clearable
            filterable
            :popper-append-to-body="false"
          >
            <!-- <el-option label="全部" :value=null></el-option> -->
            <el-option
              v-for="typeValue in permissionList"
              :key="typeValue.id"
              :label="typeValue.name"
              :value="typeValue.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="用户名称：">
          <el-input
            v-model="userName"
            placeholder="请输入"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            class="common-btn-primary left"
            size="small"
            @click="asyncGetTableData"
            >查询</el-button
          >
          <el-button class="common-btn-solid" size="small" @click="onClickRest"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div class="common-table-box">
      <div class="common-table-btn-box">
        <el-button class="common-btn-primary" size="small" @click="onclickAdd"
          >添加用户组</el-button
        >
      </div>
      <el-table :data="tableData" border>
        <el-table-column
          label="ID"
          width="110"
          prop="batchNo"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="alias"
          label="用户组名称"
          min-width="100"
          align="left"
        >
        </el-table-column>
        <el-table-column
          prop="alias"
          label="用户组描述"
          min-width="100"
          align="center"
        >
        </el-table-column>
        <el-table-column prop="alias" label="姓名" min-width="100" align="left">
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button
              v-has="'APM_edit'"
              class="common-btn-text"
              @click="onClickEdit(scope.row)"
              ><i class="icon-ali-bianji"></i>编辑</el-button
            >
            <el-button
              v-has="'APM_edit'"
              class="common-btn-text"
              @click="onClickPowerEdit(scope.row.id)"
              ><i class="icon-ali-bianji"></i>用户组权限</el-button
            >
            <el-button
              v-has="'APM_edit'"
              class="common-btn-text"
              @click="onClickEditGroup(scope.row.id)"
              ><i class="icon-ali-bianji"></i>组内用户管理</el-button
            >
            <el-button
              v-has="'APM_delete'"
              class="common-btn-text"
              @click="onClickDelete(scope.row.id)"
            >
              <i class="icon-ali-shanchu"></i>删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="pageSizeChange"
        @current-change="currentPageChange"
        :current-page="currentPage"
        :page-sizes="[100, 200, 300, 400]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog
      :title="title[infoType]"
      :visible.sync="isDialogVisible"
      :close-on-click-modal="false"
      :before-close="onClickCancelSave"
      custom-class="dialog-form"
      width="485px"
    >
      <el-form :label-width="formLabelWidth">
        <el-form-item label="用户组名称：" required>
          <el-input
            v-model.trim="dialogName"
            clearable
            :maxlength="20"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户组描述：">
          <el-input
            v-model="description"
            type="textarea"
            clearable
            :maxlength="50"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="common-footer-box active">
        <el-button
          class="common-btn-primary "
          size="small"
          @click="onClickAddSaveData"
          >保存</el-button
        >
        <el-button size="small" @click="onClickCancelSave">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="用户组权限"
      :visible.sync="isDialogPower"
      :close-on-click-modal="false"
      :before-close="onClickCancelSave"
      custom-class="dialog-form"
      width="955px"
      ><!-- width="785px" -->
      <div class="power-list-box">
        <div class="power-item-box">
          <div class="menu-name model">模块</div>
          <div class="btn-name">
            <el-checkbox
              v-model="checkedAll"
              @change="onChangeAll"
              :indeterminate="isFullChecked"
              >全选</el-checkbox
            >
          </div>
          <div class="btn-name">功能</div>
        </div>
        <div
          class="power-item-box"
          v-for="(item, index) in powerList"
          :key="index"
        >
          <div v-for="(btnItem, idx) in item" :key="idx">
            <div
              class="menu-name"
              :class="{ active: idx == 0, right: idx == 1 }"
            >
              <span v-if="idx === 0">{{ btnItem.powerName }}</span>
              <el-checkbox
                v-if="idx === 1"
                v-model="btnItem.checkFlag"
                :indeterminate="btnItem.isFullChecked"
                @change="onChangeMenu($event, index)"
                >{{ btnItem.powerName }}</el-checkbox
              >
              <el-checkbox
                v-else-if="idx !== 0 && idx !== 1"
                v-model="btnItem.checkFlag"
                @change="onChangeBtn($event, index)"
                >{{ btnItem.powerName }}</el-checkbox
              >
            </div>
          </div>
        </div>
      </div>
      <div class="common-footer-box active">
        <el-button
          class="common-btn-primary "
          size="small"
          @click="onClickAddSavePower"
          >保存</el-button
        >
        <el-button size="small" @click="onClickCancelSave">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="组内用户管理"
      :visible.sync="isDialogGroup"
      :close-on-click-modal="false"
      :before-close="onClickCancelSave" 
      custom-class="dialog-form"
      width="655px"
      ><!-- width="785px" -->
      <div class="content">
        <div class="content-item">
            <div class="item-desc">组内用户</div>
            <div class="item-checkbox">
              <el-checkbox  v-for="(item, idx) in inGroup" :key="idx" v-model="item.checked">{{item.name}}</el-checkbox>
            </div>
        </div>
        <div class="content-item">
            <div class="item-desc">组外用户</div>
            <div class="item-checkbox">
              <el-checkbox  v-for="(item, idx) in outGroup" :key="idx" v-model="item.checked">{{item.name}}</el-checkbox>
            </div>
        </div>
      </div>  
      <div class="common-footer-box active">
        <el-button
          class="common-btn-primary "
          size="small"
          @click="onClickAddSaveGroup"
          >确定</el-button
        >
        <el-button size="small" @click="onClickCancelSave">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import watchScroll from 'utils/watchScroll'

export default {
  data() {
    return {
      loading: false,
      currentPage: 1,
      pageSize: 100,
      total: 0,
      permissionList: [], //所属用户组
      tableData: [], //表格数据
      userName: "", //用户名称
      name: "", //用户组名称

      infoType: 1, //1->新增 2->编辑
      title: { "1": "添加用户组", "2": "编辑用户组" },
      userId: "",
      isDialogVisible: false,
      description: "",
      dialogName: "", //弹框用户组名称
      formLabelWidth: "150px",
      url: {
        "1": "/experimentGroup/saveExperimentGroup",
        "2": "/experimentGroup/updateExperimentGroup",
      },
      powerList: [],
      isDialogPower: false,//用户权限弹框
      isDialogGroup: false,//用户组弹框
      checkedAll: true,
      isFullChecked: false,
      Flags: false,//???
      inGroup:[{id:1,name:'哈哈哈',checked:true},{id:2,name:'哈哈笑',checked:true}],//组内数据
      outGroup:[{id:1,name:'哈哈哈',checked:true},{id:2,name:'哈哈笑',checked:true}],//组外数据
    };
  },
  created() {
    
    /*  this.asyncGetPermissionList();
      this.asyncGetTableData(); */
  },
  mounted() {
    /*  this.$nextTick(() => {
        document.querySelector('.M_content').addEventListener('scroll', watchScroll);
        window.addEventListener('resize', watchScroll);
      }); */
  },
  methods: {
    //点击--确定用户组内弹框
    onClickAddSaveGroup(){
       let inGroup = this.inGroup.filter((n) => !n.checked).map(v => v.id).join(',');
       let outGroup = this.outGroup.filter((n) => n.checked).map(v => v.id).join(',');
        console.log(inGroup);
        console.log(outGroup);
      this.$axios
          .get('/experimentGroup/updateUserGroupId?groupId='+this.userId+'&innerIds'+inGroup+'=&outIds='+outGroup)
          .then((res) => {
            if (res.data.code === 200) {
              this.isDialogGroup = false;
            } else {
              this.$message.error(res.data.msg);
            }
          });
    },
    //点击--编辑用户组
    onClickEditGroup(id){
      this.userId = id;
      this.$axios
          .get('/experimentGroup/getUserInfoForByExperimentGroupId?id='+this.userId)
          .then((res) => {
            if (res.data.code === 200) {
              this.inGroup = res.data.data.innerMap||[];
              this.outGroup = res.data.data.outMap||[];
              this.isDialogGroup = true;
            } else {
              this.$message.error(res.data.msg);
            }
          });
    },
   //全选
    onChangeAll(val) {
      this.commonFnCheckboxAll(val);
    },
    //最高级的全选
    commonFnCheckboxAll(flag) {
      this.powerList.forEach((item, index) => {
        item.forEach((obj, idx) => {
          if (idx == 1) {
            obj.isFullChecked = false;
          }
          if (idx >= 1) {
            obj.checkFlag = flag;
          }
        });
      });
      this.isFullChecked = false;
    },
    //修改菜单父级
    onChangeMenu(val, index) {
      console.log(val, index);
      this.commonFnCheckbox(index, val);
      this.isCheckboxAll();
    },
    isCheckboxAll() {
      let itemCheckedArr = [];
      this.powerList.forEach((item, index) => {
        item.forEach((obj, idx) => {
          if (idx == 1 && obj.checkFlag) {
            itemCheckedArr.push(obj.checkFlag);
          }
        });
      });
      if (this.powerList.length === itemCheckedArr.length) {
        this.isFullChecked = false;
        this.checkedAll = true;
      } else {
        if (itemCheckedArr.length === 0) {
          this.isFullChecked = false;
        } else {
          this.isFullChecked = true;
        }
        this.checkedAll = false;
      }
    },
    //某一行的 全选效果
    commonFnCheckbox(index, flag) {
      this.powerList[index].forEach((obj, idx) => {
        if (idx == 1) {
          obj.isFullChecked = false;
        }
        if (idx >= 1) {
          obj.checkFlag = flag;
        }
      });
    },
    //修改菜单子级按钮
    onChangeBtn(val, index) {
      let LEN;
      let checkedArr = [];
      if (this.powerList[index].length >= 4) {
        LEN = this.powerList[index].length - 2;
        this.powerList[index].forEach((obj, idx) => {
          if (idx > 1 && obj.checkFlag) {
            checkedArr.push(obj.checkFlag);
          }
        });
        if (checkedArr.length === LEN) {
          this.powerList[index][1].checkFlag = true;
          this.powerList[index][1].isFullChecked = false;
        } else {
          if (checkedArr.length > 0) {
            this.powerList[index][1].checkFlag = false;
            this.powerList[index][1].isFullChecked = true;
          } else if (checkedArr.length == 0) {
            this.powerList[index][1].checkFlag = false;
            this.powerList[index][1].isFullChecked = false;
          }
        }
      } else {
        this.commonFnCheckbox(index, val);
      }
      this.isCheckboxAll();
    },
    //保存-用户组权限
    onClickAddSavePower() {
      let itemCheckedArr = [];
      this.powerList.forEach((item, index) => {
        item.forEach((obj, idx) => {
          if (idx > 1 && obj.checkFlag) {
            itemCheckedArr.push(obj.id);
          }
        });
      });
      this.$axios
        .get('/experimentGroup/updatePowerIdsByGroupId?groupId='+this.userId+'&powerIds='+itemCheckedArr.join(','))
        .then((res) => {
          if (res.data.code === 200) {
            this.onClickCancelSave();
          } else {
            this.$message.error(res.data.msg);
          }
        });
    },
    //编辑用户组权限
    onClickPowerEdit(id) {
      this.userId = id;
      this.$axios
          .get("/experimentGroup/getPowerVoByGroupId?groupId=" + id)
          .then((res) => {
            if (res.data.code === 200) {
               this.powerList = res.data.data || [];
               this.powerList.forEach((item, index) => {
                item.forEach((obj, idx) => {
                  if (idx == 1) {
                    obj.isFullChecked = obj.checkFlag;
                  }
                });
              });
               this.isDialogVisible = true;
            } else {
              this.$message.error(res.data.msg);
            }
          });
    },
    //获取列表数据
    asyncGetTableData() {
      this.loading = true;
      this.$axios
        .get("/experimentGroup/listExperimentGroup", {
          params: {
            pageSize: this.pageSize,
            pageNum: this.currentPage,
            name: this.name,
            userName: this.userName,
          },
        })
        .then((res) => {
          this.loading = false;
          if (res.data.code === 200) {
            this.tableData = [];
            this.total = res.data.data.total;
          } else {
            this.$message.error(res.data.msg);
          }
        });
    },
    //重置筛选数据
    onClickRest() {
      this.pageSize = 10;
      this.currentPage = 1;
      this.name = "";
      this.userName = "";
      this.asyncGetTableData();
    },
    //获取所有分组下拉列表
    asyncGetPermissionList() {
      this.$axios.get("/experimentGroup/getExperimentGroupList").then((res) => {
        if (res.data.code === 200) {
          this.permissionList = [...res.data.data];
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    //用户信息--弹框交互
    onClickCancelSave() {
      this.isDialogVisible = false;
      this.isDialogGroup = false;
      this.isDialogPower = false; 
      this.description = "";
      this.dialogName = "";
      this.userId = "";
    },
    //保存用户信息
    onClickAddSaveData() {
      if (!this.dialogName) {
        this.$message.error("用户组名称不能为空");
        return;
      }
      this.$axios
        .post(url[this.infoType], {
          id: this.userId,
          description: this.description,
          name: this.dialogName,
        })
        .then((res) => {
          if (res.data.code === 200) {
            this.onClickCancelSave();
            this.asyncGetTableData();
          } else {
            this.$message.error(res.data.msg);
          }
        });
    },
    //点击添加
    onclickAdd() {
      this.infoType = 1;
      this.isDialogVisible = true;
    },
    //编辑
    onClickEdit(item) {
      this.infoType = 2;
      this.userId = item.id;
      this.description = item.description;
      this.name = item.name;
      this.isDialogVisible = true;
    },
    
    //删除???
    onClickDelete(id) {
      this.$confirm("确认删除该分组吗？", "删除确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        showClose: false,
        type: "warning",
        center: true,
        customClass: "common-confirm-box",
        confirmButtonClass: "common-btn-primary",
        cancelButtonClass: "common-btn-text",
      }).then(() => {
        this.$axios
          .get("/experimentGroup/deleteExperimentGroup?id=" + id)
          .then((res) => {
            if (res.data.code === 200) {
              this.asyncGetTableData();
            } else {
              this.$message.error(res.data.msg);
            }
          });
      });
    },
    pageSizeChange(val) {
      this.pageSize = val;
      this.asyncGetTableData();
    },
    currentPageChange(val) {
      this.currentPage = val;
      this.asyncGetTableData();
    },
  },
};
</script>
<style scoped>
.power-list-box {
  margin-bottom: 50px;
  /* height: calc(100vh - 280px); */
  overflow-y: auto;
  border: 1px solid #e9e9e9;
}
.power-item-box {
  display: flex;
  position: relative;
  height: 40px;
  align-items: center;
  font-size: 16px;
  background-color: rgba(242, 243, 246, 0.4);
  border-bottom: 1px solid #e9e9e9;
}
.power-item-box:last-child {
  border-bottom: none;
}
.power-item-box:nth-child(even) {
  background-color: #f2f3f6;
}
.power-item-box::before,
.power-item-box::after {
  content: "";
  position: absolute;
  width: 1px;
  height: inherit;
  top: 0;
  left: 110px;
  background-color: #e4eaf2;
}
.power-item-box::after {
  left: 195px;
}

.menu-name {
  flex: 0 1 110px;
  margin-right: 20px;
}
.menu-name.right {
  margin-right: 35px;
}

.menu-name.active {
  width: 110px;
  padding-left: 26px;
}
.btn-name {
  flex: 0 1 90px;
  text-align: left;
}

.model {
  padding-left: 39px;
}
.content {
  min-height: 200px;
}
.content-item {
  display: flex;
}
.content-item {
  display: flex;
  margin-bottom: 25px;
}
.item-desc {
  flex: 0 0 75px;
}
.item-checkbox {
  flex: 1;
}
</style>
